package loginService

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	"iristest/common/date"
	"iristest/common/encryption"
	"iristest/common/log"
	"iristest/common/middleware"
	"iristest/common/res"
	"iristest/dao/userDao2"
	"iristest/do/user"
)

type ILoginService interface {
	Login(ctx iris.Context) res.Result
	Register(ctx iris.Context) res.Result
}
type LoginService struct {
	ud userDao2.IUserDao
}

func New() ILoginService {
	return &LoginService{
		ud: userDao2.New(),
	}
}

func (ls *LoginService) Login(ctx iris.Context) res.Result {
	username := ctx.FormValue("username")
	password := ctx.FormValue("password")
	if len(username) == 0 {
		return res.FormatNulls("用户名不能为空")
	}
	if len(password) == 0 {
		return res.FormatNulls("密码不能为空")
	}
	_username, err := encryption.EncryptByAes(username)
	if err != nil {
		log.Err(err, "username ESB encrypt failed")
		return res.Errors("用户名加密失败")
	}
	_password := encryption.Md5(password)
	ui, err := ls.ud.SelectInfoByUsername(_username, _password)
	if err != nil {
		return res.Errors("用户名或密码错误")
	}
	if (*ui).Status == 4 {
		return res.NotFounds("该账号已被删除")
	}
	tk := middleware.GenerateToken(&middleware.TokenInfo{
		AppId:    12345,
		UserId:   ui.UserId,
		Username: username,
	})
	rs := make(map[string]any)
	rs["token"] = tk
	rs["userInfo"] = *ui
	sessions.Get(ctx).Set("token", tk)
	return res.Success(rs)
}

func (ls *LoginService) Register(ctx iris.Context) res.Result {
	username := ctx.FormValue("username")
	password := ctx.FormValue("password")
	name := ctx.FormValue("name")
	if len(username) == 0 {
		return res.FormatNulls("用户名不能为空")
	}
	if len(password) == 0 {
		return res.FormatNulls("密码不能为空")
	}
	if len(name) == 0 {
		name = username
	}
	_username, err := encryption.EncryptByAes(username)
	if err != nil {
		log.Err(err, "username ESB encrypt failed")
		return res.Errors("用户名加密失败")
	}
	u1 := &user.User{
		Username:         _username,
		Password:         encryption.Md5(password),
		RegistrationTime: date.TimeUnix(),
		LastLoginTime:    date.TimeUnix(),
		Status:           0,
	}
	userId := ls.ud.InsertUser(u1)
	u2 := &user.UserInfo{
		UserId:   userId,
		Name:     name,
		Photo:    "http://img.jjheiy.com/test/3.webp",
		Sex:      0,
		Birthday: date.TimeUnix(),
		Role:     1,
		Status:   0,
	}
	ls.ud.InsertUserInfo(u2)
	tk := middleware.GenerateToken(&middleware.TokenInfo{
		AppId:    12345,
		UserId:   userId,
		Username: username,
	})
	rs := make(map[string]any)
	rs["token"] = tk
	rs["userInfo"] = *u2
	sessions.Get(ctx).Set("token", tk)
	return res.Success(rs)
}
